package com.example.teacherservice.service;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.Chapter;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.repository.ChapterRepository;
import com.example.teacherservice.repository.CourseRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ChapterService {
    private final ChapterRepository chapterRepository;
    private final CourseRepository courseRepository;
    private final FileStorageService fileStorageService;


    @Transactional
    public Chapter saveChapter(Chapter chapter) {
        // 设置创建时间和更新时间
        chapter.setCreateTime(LocalDateTime.now());
        chapter.setUpdateTime(LocalDateTime.now());
        chapter.setDeleted(0);

        // 如果是新增章节，设置排序值为当前最大值+1
        if (chapter.getId() == null) {
            Integer maxSortOrder = chapterRepository.findMaxSortOrderByCourseId(chapter.getCourseId())
                    .orElse(0);
            chapter.setSortOrder(maxSortOrder + 1);
        }

        return chapterRepository.save(chapter);
    }

    @Transactional
    public Chapter updateChapter(Chapter chapter) {
        Chapter existingChapter = chapterRepository.findById(chapter.getId())
                .orElseThrow(() -> new RuntimeException("章节不存在"));

        // 更新字段
        existingChapter.setTitle(chapter.getTitle());
        existingChapter.setUrl(chapter.getUrl());
        existingChapter.setIndex(chapter.getIndex());
        existingChapter.setUpdateTime(LocalDateTime.now());

        return chapterRepository.save(existingChapter);
    }

    @Transactional
    public void deleteChapter(Long id) {
        Chapter chapter = chapterRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("章节不存在"));

        // 逻辑删除
        chapter.setDeleted(1);
        chapter.setUpdateTime(LocalDateTime.now());
        chapterRepository.save(chapter);

        // 重新排序剩余章节
        reorderChaptersAfterDelete(chapter.getCourseId());
    }

    public Chapter getChapterInfo(Long id) {
        return chapterRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("章节不存在"));
    }

    public List<Chapter> getNestedTreeListByTeacher(Long courseId) {
        return chapterRepository.findByCourseIdAndDeletedOrderBySortOrder(courseId, 0);
    }

    @Transactional
    public void updateChapterIndex(Long courseId, Integer oldIndex, Integer newIndex) {
        // 实现章节顺序交换逻辑
        Chapter chapterToMove = chapterRepository.findByCourseIdAndIndex(courseId, oldIndex)
                .orElseThrow(() -> new RuntimeException("章节不存在"));

        Chapter chapterToSwap = chapterRepository.findByCourseIdAndIndex(courseId, newIndex)
                .orElseThrow(() -> new RuntimeException("章节不存在"));

        // 交换index值
        Integer tempIndex = chapterToMove.getIndex();
        chapterToMove.setIndex(chapterToSwap.getIndex());
        chapterToSwap.setIndex(tempIndex);

        // 更新排序值
        chapterToMove.setSortOrder(newIndex);
        chapterToSwap.setSortOrder(oldIndex);

        chapterRepository.save(chapterToMove);
        chapterRepository.save(chapterToSwap);
    }


    private void reorderChaptersAfterDelete(Long courseId) {
        List<Chapter> chapters = chapterRepository.findByCourseIdAndDeletedOrderBySortOrder(courseId, 0);

        for (int i = 0; i < chapters.size(); i++) {
            chapters.get(i).setSortOrder(i + 1);
            chapters.get(i).setIndex(i + 1);
        }

        chapterRepository.saveAll(chapters);
    }

    // 2. 统一使用toDTO方法
    private ChapterDTO toDTO(Chapter chapter) {
        return ChapterDTO.builder()
                .id(chapter.getId())
                .courseId(chapter.getCourseId())
                .index(chapter.getIndex())
                .title(chapter.getTitle())
                .url(chapter.getUrl())
                .sortOrder(chapter.getSortOrder())
                .createTime(chapter.getCreateTime())
                .updateTime(chapter.getUpdateTime())
                .build();
    }

    @Transactional
    public List<ChapterDTO> addChaptersToCourse(Long courseId, List<ChapterCreateRequest> requests) {
        if (!courseRepository.existsById(courseId)) {
            throw new ResourceNotFoundException("课程不存在");
        }

        // 使用final数组解决lambda限制
        final int[] currentOrder = {chapterRepository.findMaxSortOrderByCourseId(courseId).orElse(0)};

        List<Chapter> chapters = requests.stream()
                .filter(req -> req.getTitle() != null && !req.getTitle().isBlank())
                .map(req -> {
                    Chapter chapter = new Chapter();
                    chapter.setCourseId(courseId);
                    chapter.setTitle(req.getTitle());
                    chapter.setUrl(req.getUrl());
                    chapter.setIndex(req.getIndex() != null ? req.getIndex() : 0);
                    chapter.setSortOrder(++currentOrder[0]);  // 直接操作数组元素
                    chapter.setCreateTime(LocalDateTime.now());
                    chapter.setUpdateTime(LocalDateTime.now());
                    chapter.setDeleted(0);
                    return chapter;
                })
                .collect(Collectors.toList());

        List<Chapter> savedChapters = chapterRepository.saveAll(chapters);

        return savedChapters.stream()
                .map(this::toDTO)
                .collect(Collectors.toList());
    }

    @Transactional
    public void updateChapterOrder(ChapterOrderUpdateRequest request) {
        List<Chapter> chapters = chapterRepository.findAllById(request.getChapterIds());

        if (chapters.size() != request.getChapterIds().size()) {
            throw new ResourceNotFoundException("部分章节不存在");
        }

        // 使用final数组包装循环变量
        final int[] order = {1}; // 从1开始计数

        request.getChapterIds().forEach(chapterId -> {
            chapters.stream()
                    .filter(c -> c.getId().equals(chapterId))
                    .findFirst()
                    .ifPresent(c -> {
                        c.setSortOrder(order[0]++); // 使用并递增数组元素
                        c.setUpdateTime(LocalDateTime.now());
                    });
        });

        chapterRepository.saveAll(chapters);
    }

    // ChapterService.java
    public ChapterVideoInfoDTO getVideoInfo(Long courseId, Long chapterId) {
        Chapter chapter = chapterRepository.findById(chapterId)
                .orElseThrow(() -> new ResourceNotFoundException("章节不存在"));

        if (!chapter.getCourseId().equals(courseId)) {
            throw new ResourceNotFoundException("章节不属于该课程");
        }

        // 使用默认值填充缺少的字段
        return ChapterVideoInfoDTO.builder()
                .courseId(courseId)
                .courseName(courseRepository.findById(courseId)
                        .orElseThrow(() -> new ResourceNotFoundException("课程不存在"))
                        .getCouName())
                .chapterId(chapterId)
                .chapterTitle(chapter.getTitle())
                .videoUrl(chapter.getUrl())
                .coverUrl(null) // 或使用默认封面URL
                .duration(null) // 或估算时长
                .viewCount(null) // 无法统计播放量
                .updateTime(chapter.getUpdateTime())
                .build();
    }

    @Transactional
    public ChapterDTO createChapter(ChapterCreateRequest request) {
        Chapter chapter = new Chapter();
        chapter.setCourseId(request.getCourseId());
        chapter.setTitle(request.getTitle());
        chapter.setUrl(request.getUrl());
        chapter.setDuration(request.getDuration()); // 设置视频时长
        chapter.setDeleted(0);

        // 自动计算下一个索引值
        long nextIndex = chapterRepository.countByCourseIdAndDeleted(request.getCourseId(), 0) + 1;
        chapter.setIndex((int)nextIndex);

        // 设置排序值（与index保持一致）
        chapter.setSortOrder((int)nextIndex);

        chapter.setCreateTime(LocalDateTime.now());
        chapter.setUpdateTime(LocalDateTime.now());

        return toDTO(chapterRepository.save(chapter));
    }

    @Transactional
    public ChapterDTO updateChapter(Long chapterId, ChapterUpdateRequest request) {
        Chapter chapter = chapterRepository.findById(chapterId)
                .orElseThrow(() -> new RuntimeException("章节不存在"));

        // 更新URL时重新解析时长
        if (request.getUrl() != null && !request.getUrl().equals(chapter.getUrl())) {
            try {
                long duration = fileStorageService.parseVideoDuration(request.getUrl());
                chapter.setDuration(duration);
            } catch (Exception e) {
                System.out.println("视频时长解析失败: "+request.getUrl());
                chapter.setDuration(0L);
            }
        } else if (request.getDuration() != null) {
            chapter.setDuration(request.getDuration());
        }

        chapter.setTitle(request.getTitle());
        chapter.setUrl(request.getUrl());
        chapter.setIndex(request.getIndex());
        chapter.setUpdateTime(LocalDateTime.now());

        chapter = chapterRepository.save(chapter);

        return toDTO(chapter);
    }
}